package com.zzw.common;

import com.zzw.common.exception.CommonException;
import com.zzw.requestcontext.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.zzw.common.ApiCommonResponse.SYSTEM_ERROR;
import static com.zzw.common.ApiCommonResponse.SYSTEM_EXCEPTION;

/**
 * @author Administrator
 */
abstract public class DefaultCommonService<T extends ApiRequest, E> implements CommonApi<T, E> {

    private static final Logger logger = LoggerFactory.getLogger(DefaultCommonService.class);

    public abstract void checkParam(T request) throws CommonException;

    @Override
    public ApiCommonResponse<E> process(T request) {
        RequestContext requestContext = RequestContext.getInstance();
        try {
            checkParam(request);
            return ApiCommonResponse.of(requestContext.getSn(), bussiness(request));
        } catch (CommonException e) {
            logger.error("sn:{},common exception", requestContext.getSn(), e);
            return ApiCommonResponse.of(requestContext.getSn(), e.status, e.message);
        } catch (Exception e) {
            logger.error("sn:{},exception", requestContext.getSn(), e);
            return ApiCommonResponse.of(requestContext.getSn(), SYSTEM_EXCEPTION, "system exception");
        } catch (Throwable tx) {
            logger.error("sn:{},Throwable", requestContext.getSn(), tx);
            return ApiCommonResponse.of(requestContext.getSn(), SYSTEM_ERROR, "system error");
        }
    }

    public abstract E bussiness(T request) throws Exception;
}
